package com.dizang.es.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.dizang.es.entity.WgProduct;
import com.dizang.es.repository.WgProductRepository;
import com.dizang.es.utils.BaseRespone;
import com.dizang.es.utils.ResultUtil;

import java.util.*;

/**
 * 
 * 需要一个工具将MySQL的数据导入Elasticsearch，因为一般不会在代码中添加数据到es。
 * 为了保持mysql数据是和es是一致的，就用logstash方式同步过去给es
 * 一般在这里做查询就可以了
 * @author kelvin
 *
 */
@RestController
@RequestMapping("/wgproduct")
public class WgProductController {
    @Autowired
    private WgProductRepository wgProductRepository;

    @PostMapping("/add")
    public BaseRespone add(@RequestBody WgProduct wgProduct) {
        System.out.println(wgProduct.toString());
        System.out.println(wgProduct instanceof WgProduct);// true
        wgProductRepository.save(wgProduct);
        return ResultUtil.resultCode(200, "添加商品成功"); // ResultUtil工具换成自己的就行
    }

    // 根据Id查询
    @GetMapping("/get/{id}")
    public BaseRespone getById(@PathVariable String id) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (StringUtils.isEmpty(id))
            return ResultUtil.resultCode(500, "Id为空");
        // 【java8新特性】Optional详解 https://www.jianshu.com/p/d81a5f7c9c4e
        Optional<WgProduct> wgProductOptional = wgProductRepository.findById(id);
        if (wgProductOptional.isPresent()) {// isPresent()方法用于判断包装对象的值是否非空
            WgProduct wgProduct = wgProductOptional.get();
            result.put("商品信息", wgProduct);
            return ResultUtil.resultSuccess(result);
        }
        return ResultUtil.resultError(result);
    }

    // 查询所有
    @GetMapping("/getall")
    public BaseRespone getAll() {
        Map<String, Object> result = new HashMap<String, Object>();
        Iterable<WgProduct> iterable = wgProductRepository.findAll();
        List<WgProduct> list = new ArrayList<WgProduct>();
        iterable.forEach(list::add);
        result.put("所有商品", list);
        return ResultUtil.resultSuccess(result);
    }

    //根据ID修改
    @PostMapping("/update")
    public BaseRespone updateById(@RequestBody WgProduct wgProduct) {
        String id = wgProduct.getId();
        if (StringUtils.isEmpty(id))
            return ResultUtil.resultCode(500, "Id为空");
        wgProductRepository.save(wgProduct);
        return ResultUtil.resultCode(200, "修改商品成功");
    }

    //根据ID删除
    @DeleteMapping("/delete/{id}")
    public BaseRespone deleteById(@PathVariable String id) {
        if (StringUtils.isEmpty(id))
            return ResultUtil.resultCode(500, "Id为空");
        wgProductRepository.deleteById(id);
        return ResultUtil.resultCode(200, "删除商品成功");
    }
}